<template>
    <div>
      <input v-model="receiveMsg"><br>
      <input v-model="sendMsg">
      <lemon-imui ref="IMUI" :user="user"
                  @pull-messages="handlePullMessages"
                  @send="handleSend">

        <template #cover>
          <div class="cover">
            <span><b>Lemon</b> IMUI</span>
          </div>
        </template>
      </lemon-imui>
    </div>
</template>

<script>
  // 非 ESModule
  // const RongIMLib = require('@rongcloud/imlib-v4') 需修改为
  const getTime = () => new Date().getTime();
  const generateRandId = () => Math.random().toString(36).substr(-8);

  const im =null;
    export default {
        name: "",
        data(){
          return{
            receiveMsg:'',
            sendMsg:'',
            rongtoken:'',
            user:{
              id: "1",
              displayName: "June",
              avatar: "",
            },
            userlist:[],
            msg:{},
            messages:[]
          }
        },
      methods:{
          send:function(){

          },
        listen:function (token) {
         var _this=this;
         //初始化融云的客户端
          this.im = this.$RongIMLib.init({ appkey: '8luwapkv8wxcl'});
          console.log(im)
          this.im.watch({
          // 监听消息通知
          message (event) {
            // 新接收到的消息内容
            const message = event.message;
            _this.receiveMessage(message);
          },
          // 监听 IM 连接状态变化
          status (event) {
            console.log('connection status:', event.status);
          },
          // 监听聊天室 KV 数据变更
          chatroom (event) {
            /**
             * 聊天室 KV 存储数据更新
             * @example
             * [
             *  {
             *    "key": "name",
             *    "value": "我是小融融",
             *    "timestamp": 1597591258338,
             *    "chatroomId": "z002",
             *    "type": 1 // 1: 更新（ 含:修改和新增 ）、2: 删除
             *  },
             * ]
             */
            const updatedEntries = event.updatedEntries
          },
          expansion (event) {
            /**
             * 更新的消息拓展数据
             * @example {
             *    expansion: { key: 'value' },      // 设置或更新的扩展值
             *    messageUId: 'URIT-URIT-ODMF-DURR' // 设置或更新扩展的消息 uid
             * }
             */
            const updatedExpansion = event.updatedExpansion;
            /**
             * 删除的消息拓展数据
             * @example {
             *    deletedKeys: ['key1', 'key2'],    // 设置或更新的扩展值
             *    messageUId: 'URIT-URIT-ODMF-DURR' // 设置或更新扩展的消息 uid
             * }
             */
            const deletedExpansion = event.deletedExpansion;
          }
        })
            //这个js的作用是，与融云进行连接
          this.im.connect({ token: token }).then(user => {
            console.log('链接成功, 链接用户 id 为: ', user.id);
          }).catch(error => {
            console.log('链接失败: ', error.code, error.msg);
          });
        },

        //发送消息
        handleSend(message, next, file) {
          console.log(message, next, file);
          console.log(message);
          const { currentContactId } = this.$refs.IMUI;
          this.msg.userid=currentContactId;
          this.msg.msg=message.content;
          this.$axios.post("qflive-message/message/sendMsg",this.msg).then(res=>{
            if (res.data.code==1){
              next();
            }
          })

        },
        //拉取消息列表
        handlePullMessages(contact, next) {
          const { currentContactId } = this.$refs.IMUI;

          this.$axios.post("qflive-message/message/findTalkListByToken",{uid:currentContactId}).then(res=>{
            console.log(res.data.data)
            if (res.data.data==null){
              console.log(123)
              const messages = [{
                id: generateRandId(),
                status: 'succeed',
                type: 'text',
                sendTime: 1566047865417,
                content: '你什么才能对接完？',
                toContactId: contact.id,
                fromUser:this.user
              }]
              next(messages, true);
            } else{
              next(res.data.data.messageList, true);

            }
          })
          // const messages = [{
          //   id: generateRandId(),
          //   status: 'succeed',
          //   type: 'text',
          //   sendTime: 1566047865417,
          //   content: '你什么才能对接完？',
          //   toContactId: contact.id,
          //   fromUser:this.user
          // }]


        },
        //消息列表中 持续不断的添加对话的内容
        receiveMessage:function(msg){
            //当前收件人的唯一标识
          const { currentContactId } = this.$refs.IMUI;
          const contact = this.$refs.IMUI.currentContact;;
          console.log("======"+currentContactId);
          console.log(msg);
          const data = {
            id: msg.messageUId,
            status: 'succeed',
            type: 'text',
            sendTime: msg.sentTime,
            content: msg.content.content,
            toContactId: currentContactId,
            fromUser:{
              //如果 id == this.user.id消息会显示在右侧，否则在左侧
              id:msg.senderUserId,
              displayName: contact.displayName,
              avatar:'',
            }
          };
          console.log(data);
          this.$refs.IMUI.appendMessage(data);
        },
        //初始化联系人
        initLemon:function () {
          const { IMUI } = this.$refs;
          console.log(this.userlist)
          IMUI.initContacts(this.userlist);
        }
      },
      created(){

      },
      mounted(){
          //获取到当前登录用户
        this.$axios.post("qflive-user/user/findUserByToken").then(res=>{
          this.rongtoken=res.data.data.rongToken;
          this.user.displayName=res.data.data.loginName;
          this.user.id=res.data.data.userId;
        })
        //初始化 聊天列表
        this.$axios.post("/qflive-message/message/findTalkUser").then(res=>{
          console.log(res.data)
          if (res.data.code==1) {
            // this.user.id=res.data.data.userId;
            // this.user.displayName=res.data.data.loginName;
            this.userlist=res.data.data;
            //console.log(res.data.data.messageList)
            //初始化融云的连接
            //开始监听
            this.listen(this.rongtoken);
            //初始化界面的聊天列表
            this.initLemon();

          }
          if (res.data.code=="10006"){
            this.$router.push("/")
          }
        })
      }
    }
</script>

<style scoped>

</style>
